/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.sys.controller;


import io.renren.common.utils.Constant;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysLoginLogEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.SysCaptchaService;
import io.renren.modules.sys.service.SysLoginLogService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
public class SysLoginController extends AbstractController{
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private SysLoginLogService sysLoginLogService;

	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(HttpServletRequest request, @RequestBody SysLoginForm form) {
		boolean captchaFlag = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captchaFlag){
			return R.error(501, "验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		SysLoginLogEntity log = new SysLoginLogEntity();
		log.setCreateDate(new Date());
		log.setIp(IPUtils.getIpAddr(request));
		log.setOperation("用户登录");
		log.setStatus(Constant.LoginLogStatus.SUCCESS.getValue());
		log.setUsername(form.getUsername());

		R result = null;

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			log.setStatus(Constant.LoginLogStatus.FAIL.getValue());
			result = R.error("账号或密码不正确");
		}else if(user.getStatus() == 0){
			//账号锁定
			log.setStatus(Constant.LoginLogStatus.FAIL.getValue());
			result = R.error("账号已被锁定,请联系管理员");
		}

		//保存登录日志
		sysLoginLogService.insert(log);

		if(result == null){
			//生成token，并保存到数据库
			result = sysUserTokenService.createToken(user.getUserId());
		}

		return result;
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}
	
}
